#!/usr/bin/env python
# -*- coding: utf-8 -*-

from google.appengine.api import search
import json

class Recipe():
  def __init__(self):
    self.title = ""
    self.main_photo = ""
    self.ingredients = []
    self.source = ""
    
  @classmethod
  def from_search_doc(cls, doc):
    title = doc['title'][0].value.encode('utf-8')
    ingredients = []
    for ingredient in doc['ingredient']:
      ingredients.append(ingredient.value.encode('utf-8'))
    source = doc['source'][0].value.encode('utf-8')
    main_photo = doc['main_photo'][0].value.encode('utf-8')
     
    r = cls()
    r.title = title
    r.ingredients = ingredients
    r.source = source
    r.main_photo = main_photo
    return r

  def as_search_doc(self):
    fields = [search.TextField(name='title', value=self.title)]
    for ingredient in self.ingredients:
      fields.append(search.TextField(name='ingredient', value=ingredient))
    fields.append(search.TextField(name='source', value=self.source))
    fields.append(search.AtomField(name='main_photo', value=self.main_photo))
    return search.Document(fields=fields)

  def as_json(self):
    return json.dumps(self.__dict__, ensure_ascii=False)

  @classmethod
  def from_json(cls, data):
    r = cls()
    r.title = data['title'].encode('utf-8')
    r.ingredients = []
    for i in data['ingredients']:
      r.ingredients.append(i.encode('utf-8'))
    r.main_photo = data['main_photo'].encode('utf-8')
    r.source = data['source'].encode('utf-8')
    return r